package org.example;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * Netty 核心组件关系
 * Bootstrap/ServerBootstrap
 *     ├── EventLoopGroup (boss/worker) 事件循环组，包含多个EventLoop(事件循环，处理I/O事件和任务)
 *     ├── Channel (NioSocketChannel/NioServerSocketChannel) 网络连接通道
 *     └── ChannelPipeline 处理器链, chanelHandler(业务处理器) 处理I/O事件和任务
 *         ├── ChannelHandlerContext 上下文对象
 *         ├── ChannelInboundHandler 输入处理器
 *         └── ChannelOutboundHandler 输出处理器
 */
public class NettyServer {
    public static void main(String[] args) throws InterruptedException {
        /*
         * 创建两个EventLoopGroup实例
         * bossGroup用于处理连接请求
         * workerGroup用于处理业务逻辑
         */
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            /*
             * 创建ServerBootstrap实例
             * 配置服务端参数
             */
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            /*
                             * 添加自定义处理器到管道
                             * 包括编解码器和业务处理器
                             */
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new ServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            /*
             * 绑定端口并启动服务
             * sync()方法会阻塞直到绑定完成
             */
            ChannelFuture future = bootstrap.bind(8080).sync();
            System.out.println("Server started on port 8080");

            /*
             * 等待服务端监听端口关闭
             * 这里会阻塞主线程
             */
            future.channel().closeFuture().sync();
        } finally {
            /*
             * 优雅关闭EventLoopGroup
             * 释放所有资源
             */
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}